<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>新闻分类管理</span>
          <div>
            <el-button
              type="primary"
              icon="Plus"
              class="toolbar-button is-primary"
              @click="handleAdd"
            >新增分类</el-button>
            <el-button
              type="success"
              icon="Sort"
              class="toolbar-button is-success"
              @click="handleExpandAll"
            >{{ isExpandAll ? '折叠全部' : '展开全部' }}</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
          <el-form-item label="分类名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入分类名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 树形表格 -->
      <el-table
        v-loading="loading"
        :data="categoryList"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="isExpandAll"
      >
        <el-table-column label="分类名称" align="left" min-width="200">
          <template #default="scope">
            <div class="category-info">
              <el-icon v-if="scope.row.icon" class="category-icon">
                <component :is="scope.row.icon" />
              </el-icon>
              <span class="category-name">{{ scope.row.name }}</span>
              <el-tag v-if="scope.row.level === 1" type="primary" size="small">一级</el-tag>
              <el-tag v-else-if="scope.row.level === 2" type="success" size="small">二级</el-tag>
              <el-tag v-else type="info" size="small">{{ scope.row.level }}级</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="分类描述" align="left" min-width="200">
          <template #default="scope">
            <span class="text-muted">{{ scope.row.description || '暂无描述' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" width="80">
          <template #default="scope">
            <span>{{ scope.row.sortOrder || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="新闻数量" align="center" width="100">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.newsCount || 0 }}篇</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="success"
                icon="Plus"
                @click="handleAddChild(scope.row)"
                class="table-operation-button is-success"
                size="small"
              >新增子分类</el-button>
              <el-button
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >编辑</el-button>
              <el-button
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                class="table-operation-button is-danger"
                size="small"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改分类对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="categoryFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级分类" prop="parentId" v-if="form.parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="categoryTreeOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            placeholder="请选择上级分类"
            check-strictly
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入分类描述"
            :rows="3"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类图标" prop="icon">
              <el-input v-model="form.icon" placeholder="请输入图标名称">
                <template #prepend>
                  <el-icon v-if="form.icon">
                    <component :is="form.icon" />
                  </el-icon>
                  <el-icon v-else><Picture /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号" prop="sortOrder">
              <el-input-number v-model="form.sortOrder" :min="0" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="SEO关键词" prop="keywords">
          <el-input v-model="form.keywords" placeholder="请输入SEO关键词，多个用逗号分隔" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="NewsCategory">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Sort, Search, Refresh, Edit, Delete, Picture } from '@element-plus/icons-vue'
import {
  getNewsCategoryTree,
  getNewsCategoryDetail,
  createNewsCategory,
  updateNewsCategory,
  deleteNewsCategory
} from '@/api/news'

// 响应式数据
const loading = ref(true)
const open = ref(false)
const isExpandAll = ref(false)
const title = ref('')
const queryRef = ref()
const categoryFormRef = ref()

// 列表数据
const categoryList = ref([])
const categoryTreeOptions = ref([])

// 查询参数
const queryParams = reactive({
  name: undefined,
  status: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  parentId: undefined,
  name: undefined,
  description: undefined,
  icon: undefined,
  sortOrder: 0,
  keywords: undefined,
  status: 1
})

// 表单校验规则
const rules = reactive({
  name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
  sortOrder: [{ required: true, message: '排序号不能为空', trigger: 'blur' }]
})

// 获取分类树
const getList = async () => {
  loading.value = true
  try {
    const response = await getNewsCategoryTree()
    if (response.code === 200) {
      categoryList.value = response.data || []
      // 构建树形选择器选项
      categoryTreeOptions.value = buildTreeOptions(categoryList.value)
    } else {
      ElMessage.error(response.message || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')

    // 模拟数据
    categoryList.value = [
      {
        id: 1,
        name: '科技资讯',
        description: '科技相关的新闻资讯',
        icon: 'Monitor',
        level: 1,
        sortOrder: 1,
        newsCount: 25,
        status: 1,
        createTime: '2024-01-15 10:30:00',
        children: [
          {
            id: 11,
            parentId: 1,
            name: '人工智能',
            description: 'AI相关新闻',
            icon: 'Cpu',
            level: 2,
            sortOrder: 1,
            newsCount: 12,
            status: 1,
            createTime: '2024-01-15 11:00:00'
          },
          {
            id: 12,
            parentId: 1,
            name: '区块链',
            description: '区块链技术新闻',
            icon: 'Link',
            level: 2,
            sortOrder: 2,
            newsCount: 8,
            status: 1,
            createTime: '2024-01-15 11:30:00'
          }
        ]
      },
      {
        id: 2,
        name: '教育资讯',
        description: '教育相关的新闻资讯',
        icon: 'Reading',
        level: 1,
        sortOrder: 2,
        newsCount: 18,
        status: 1,
        createTime: '2024-01-15 12:00:00',
        children: [
          {
            id: 21,
            parentId: 2,
            name: '在线教育',
            description: '在线教育相关新闻',
            icon: 'VideoPlay',
            level: 2,
            sortOrder: 1,
            newsCount: 10,
            status: 1,
            createTime: '2024-01-15 12:30:00'
          }
        ]
      },
      {
        id: 3,
        name: '行业动态',
        description: '各行业动态新闻',
        icon: 'TrendCharts',
        level: 1,
        sortOrder: 3,
        newsCount: 15,
        status: 0,
        createTime: '2024-01-15 13:00:00'
      }
    ]
    categoryTreeOptions.value = buildTreeOptions(categoryList.value)
  } finally {
    loading.value = false
  }
}

// 构建树形选择器选项
const buildTreeOptions = (data) => {
  return data.map(item => ({
    id: item.id,
    name: item.name,
    children: item.children ? buildTreeOptions(item.children) : []
  }))
}

// 搜索按钮操作
const handleQuery = () => {
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryRef.value?.resetFields()
  handleQuery()
}

// 展开/折叠全部
const handleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加分类'
}

// 新增子分类
const handleAddChild = (row) => {
  reset()
  form.parentId = row.id
  open.value = true
  title.value = '添加子分类'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  Object.assign(form, row)
  open.value = true
  title.value = '修改分类'
}

// 状态修改
const handleStatusChange = async (row) => {
  const text = row.status === 1 ? '启用' : '禁用'
  try {
    await ElMessageBox.confirm('确认要"' + text + '""' + row.name + '"分类吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await updateNewsCategory(row.id, { status: row.status })
    if (response.code === 200) {
      ElMessage.success(text + '成功')
    } else {
      ElMessage.error(response.message || text + '失败')
      row.status = row.status === 1 ? 0 : 1
    }
  } catch (error) {
    if (error !== 'cancel') {
      row.status = row.status === 1 ? 0 : 1
      ElMessage.error(text + '失败')
    }
  }
}

// 删除按钮操作
const handleDelete = async (row) => {
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该分类下存在子分类，请先删除子分类')
    return
  }

  if (row.newsCount > 0) {
    ElMessage.warning('该分类下存在新闻，请先移动或删除相关新闻')
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除分类"' + row.name + '"吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await deleteNewsCategory(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: undefined,
    parentId: undefined,
    name: undefined,
    description: undefined,
    icon: undefined,
    sortOrder: 0,
    keywords: undefined,
    status: 1
  })
  categoryFormRef.value?.resetFields()
}

// 提交表单
const submitForm = () => {
  categoryFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          const response = await updateNewsCategory(form.id, form)
          if (response.code === 200) {
            ElMessage.success('修改成功')
          } else {
            ElMessage.error(response.message || '修改失败')
            return
          }
        } else {
          const response = await createNewsCategory(form)
          if (response.code === 200) {
            ElMessage.success('新增成功')
          } else {
            ElMessage.error(response.message || '新增失败')
            return
          }
        }
        open.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 工具函数
const parseTime = (time, pattern = '{y}-{m}-{d} {h}:{i}:{s}') => {
  if (!time) return ''
  return time
}

// 页面加载
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

.category-info {
  display: flex;
  align-items: center;
  gap: 8px;

  .category-icon {
    color: #409eff;
    font-size: 16px;
  }

  .category-name {
    font-weight: 500;
    color: #303133;
  }
}

.dialog-footer {
  text-align: right;
}

// 树形表格样式
:deep(.el-table) {
  .el-table__row {
    &:hover {
      background-color: #f5f7fa;
    }
  }

  .el-table__expand-icon {
    color: #409eff;
  }
}

// 树形选择器样式
:deep(.el-tree-select) {
  .el-tree-node__content {
    height: auto;
    padding: 4px 0;
  }
}
</style>
